import { readFileSync, writeFileSync } from 'fs'
import { globby } from 'globby'
import { execTranslate } from './翻译.mjs'

export async function extractAllI18nKeys() {
  const paths = await globby(['*.{js,ts,vue}', './**/*.{js,ts,vue}', '!node_modules/**'])
  const oldChineseStr = readFileSync('./locales/en.json', { encoding: 'utf-8' })
  const chineseDict = {}
  paths.forEach((path) => {
    const fileContent = readFileSync(path, { encoding: 'utf-8' })
    const i18nKeys = Array.from(fileContent.matchAll(/\$mt\(([\s\S]*?)\)/g))
    if (!i18nKeys.length) return
    i18nKeys.forEach(([x1, key]) => {
      key = key.trim()
      key.replace(/['"](.*)['"]/g, (x2, str) => (key = str))
      chineseDict[key] = key
    })
  })
  if (JSON.stringify(chineseDict, null, 2) === oldChineseStr) return
  const languageFiles = await globby(['./locales/*.json'])
  // 是否需要清除掉其他未使用的翻译
  // languageFiles.forEach((p) => writeFileSync(p, '{}'))
  writeFileSync('./locales/en.json', JSON.stringify(chineseDict, null, 2))
}

const watchDir = './'
const watchOptions = { recursive: true }
extractAllI18nKeys().then(async () => {
  await new Promise((resolve) => setTimeout(resolve, 1200))
  await execTranslate()
})
